<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <el-button type="primary" size="small" @click="setTime('今天')"
          >今天
        </el-button>
        <el-button type="primary" size="small" @click="setTime('昨天')"
          >昨天
        </el-button>
        <el-button type="primary" size="small" @click="setTime('本月')"
          >本月
        </el-button>
      </template>
   
      <template slot-scope="{}" slot="rpsNoSearch">
        <select-page-mer ref="searchRpsSelect" placeholder-text="门店" :searchParams="searchParams" label="rpsName" value="rpsNo" :select.sync="search.rpsNo" :url="website.searchLink.rpsUrl" filter-key="searchParam"></select-page-mer>
      </template>

      <template slot-scope="{disabled,size}" slot="beginTimeSearch">
        <el-date-picker v-model="search.beginTime" type="datetime" :editable="false" :clearable="false" value-format='yyyy-MM-dd HH:mm:ss' @change="beginTimeChange" placeholder="请输入 交易开始日期"></el-date-picker>
      </template>
      <template slot-scope="{disabled,size}" slot="endTimeSearch">
        <el-date-picker v-model="search.endTime" type="datetime" :editable="false" :clearable="false" default-time="23:59:59" value-format='yyyy-MM-dd HH:mm:ss' @change="endTimeChange" placeholder="请输入 交易结束日期"></el-date-picker>
      </template>
    </avue-crud>
    <!-- 检测是否选择商户 -->
    <selectMer :dialogVisible="tipsShow" />
  </basic-container>
</template>

<script>
import { getStoreList } from "@/api/rb-merchant/dealManagement/storeStatistics";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import { dateFormat } from "@/util/date";
import selectPageMer from "@/components/select-page/select-page-mer";

export default {
  components: {
    selectPageMer
  },
  data() {
    return {
      tipsShow:false,
      form: {},
      query:  {
        beginTime: dateFormat(new Date(), "yyyy-MM") + "-01 00:00:00",
        endTime: dateFormat(new Date(), "yyyy-MM-dd") + " 23:59:59"
      },
      search: {
        beginTime: dateFormat(new Date(), "yyyy-MM") + "-01 00:00:00",
        endTime: dateFormat(new Date(), "yyyy-MM-dd") + " 23:59:59"
      },
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option:{
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 120, //搜索框标题宽度
        menuWidth: 100, //操作栏宽度
        emptyBtnText:'重置',
        // searchIcon:true,
        // searchIndex:3,
        menu:false,
        column: [
          {
            label: "门店编号",
            searchLabel: "门店",
            prop: "rpsNo",
            type: "select",
            minWidth: 140,
            overHidden:true,
            search: true,
            display:false
          },
          {
            label: "门店名称",
            prop: "rpsName",
            type: "input",
            overHidden:true,
            minWidth: 170
          },
          {
            label: "实收金额(元)",
            prop: "trueAmount",
            type: "input",
            overHidden:true,
            minWidth: 170
          },
          {
            label: "收款金额(元)",
            prop: "amount",
            type: "input",
            overHidden:true,
            minWidth: 170
          },
          {
            label: "退款金额(元)",
            prop: "refundAmount",
            type: "input",
            overHidden:true,
            minWidth: 170
          },
          {
            label: "收款笔数",
            prop: "count",
            type: "input",
            overHidden:true,
            minWidth: 170
          },
          {
            label: "退款笔数",
            prop: "refundCount",
            type: "input",
            overHidden:true,
            minWidth: 170
          },
          {
            label: "交易开始日期",
            prop: "beginTime",
            search: true,
            hide: true,
            display: false
          },
          {
            label: "交易结束日期",
            prop: "endTime",
            search: true,
            hide: true,
            display: false
          }
        ]
      },
      data: [],
      searchParams:{},
      currentMer:{
        isDay: 1 //是否日报表 
      }
    };
  },
  computed: {
    ...mapGetters(["permission","selectMer","userInfo"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.storeStatistics_view, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == "-1") {
          return (val = 0);
        } else {
          return val;
        }
      };
    }
  },
  created(){
    /* 检测是否选择了商户，没有选择跳转页面进行选择 */
    this.isSelect()
  },
  methods: {
    beginTimeChange() {
      if(this.search.endTime){
        if( new Date(this.search.beginTime).getFullYear() === new Date(this.search.endTime).getFullYear()){
          if(Date.parse(this.search.beginTime) > Date.parse(this.search.endTime)){
            this.$alert('统计开始日期不能大于结束日期', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
          }else if(Date.parse(this.search.beginTime) < Date.parse(this.search.endTime)-3600 * 1000 * 24 * 90){
            this.$alert('日期筛选间隔最大为 3个月', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            // this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
            this.search.endTime = dateFormat(new Date(this.search.beginTime),"yyyy-MM-dd")+' 23:59:59';
          }
        }else{
          if(Date.parse(this.search.beginTime) < Date.now() - 3600 * 1000 * 24 * 365 * 2){
            this.$alert('只能查询两年内的数据！', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
          }else{
            this.$alert('查询日期不能跨年', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            // this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
            this.search.endTime = dateFormat(new Date(this.search.beginTime),"yyyy-MM-dd")+' 23:59:59';
          }
        }
      }
    },
    endTimeChange() {
      if(this.search.beginTime){
        if( new Date(this.search.endTime).getFullYear() === new Date(this.search.beginTime).getFullYear()){
          if(Date.parse(this.search.endTime) < Date.parse(this.search.beginTime)){
            this.$alert('统计结束日期不能小于开始日期', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            this.search.endTime = dateFormat(new Date(this.search.beginTime),"yyyy-MM-dd")+' 23:59:59';

          }else if(Date.parse(this.search.beginTime)+3600 * 1000 * 24 * 90 < Date.parse(this.search.endTime)){
            this.$alert('日期筛选间隔最大为 3个月', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            // this.search.endTime = dateFormat(new Date(this.search.beginTime),"yyyy-MM-dd")+' 23:59:59';
            this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
          }
        }else{
          this.$alert('查询日期不能跨年', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
            // this.search.endTime = dateFormat(new Date(this.search.beginTime),"yyyy-MM-dd")+' 23:59:59';
            this.search.beginTime = dateFormat(new Date(this.search.endTime),"yyyy-MM-dd")+' 00:00:00';
        }
      }
    },
    isSelect(){
      /* userMerchantType----用户商户类型(0.无 1.集团商户 2.商户 3.门店 4.收银员) */
      if(!this.selectMer.rpiNo){
        this.tipsShow=true;
      }else if(this.selectMer.userMerchantType === 1){
        // 集团商户
        this.searchParams.rpiGroup = this.selectMer.rpiNo;

        this.currentMer.userNo = this.selectMer.rpiNo;
        this.currentMer.userMerchantType = this.selectMer.userMerchantType;
      }else  if(this.selectMer.userMerchantType === 2){
        // 商户
        this.searchParams.rpiNo = this.selectMer.rpiNo;

        this.currentMer.userNo = this.selectMer.rpiNo;
        this.currentMer.userMerchantType = this.selectMer.userMerchantType;
      }else if(this.selectMer.userMerchantType === 3){
        // 门店
        this.searchParams.rpiNo = this.selectMer.rpiNo;
        this.searchParams.rpsNo = this.selectMer.rpsNo;

        this.currentMer.userNo = this.selectMer.rpsNo;
        this.currentMer.userMerchantType = this.selectMer.userMerchantType;
      }else{
        // 收银员
        this.searchParams.rpiNo = this.selectMer.rpiNo;
        this.searchParams.rpstNo = this.selectMer.rpstNo;

        this.currentMer.userNo = this.selectMer.rpstNo;
        this.currentMer.userMerchantType = this.selectMer.userMerchantType;
      }

      // this.$refs.crud.refreshTable()
    },
    /**
     * @func 设置时间
     * @desc 点击获取点击天数时间
     * @param {Object} type - 今天，昨天，近七天
     * */
    setTime(type) {
      let date = new Date();
      this.query = {};
      if (type == "今天") {
        this.search.beginTime = dateFormat(date, "yyyy-MM-dd") +' 00:00:00';
        this.search.endTime = dateFormat(date, "yyyy-MM-dd") +' 23:59:59';
        this.page.currentPage = 1;
        this.forInSearch();
        this.refreshChange();
      } else if (type == "昨天") {
        this.search.beginTime = dateFormat(new Date(date.getTime() - 3600 * 1000 * 24 * 1),"yyyy-MM-dd")+' 00:00:00';
        this.search.endTime = dateFormat(new Date(date.getTime() - 3600 * 1000 * 24 * 1),"yyyy-MM-dd")+' 23:59:59';
        this.page.currentPage = 1;
        this.forInSearch();
        this.refreshChange();
      } else {
        // "本月"
        this.search.beginTime = dateFormat(date,"yyyy-MM")+'-01 00:00:00';
        this.search.endTime = dateFormat(date,"yyyy-MM-dd")+' 23:59:59';
        this.page.currentPage = 1;
        this.forInSearch();
        this.refreshChange();
      }
    },
    forInSearch(){
      for(let key in this.search){
        //console.log(key)
        if(this.search[key]){
          if(key.indexOf("$") == -1 ){
            this.query[key] = this.search[key]
          }
        }
      }
    },
    /**
     * @func edit,view 打开之前回调
     * @desc 点击获取点击天数时间
     * */
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    /**
     * @func 重置
     * @desc 重置查询条件
     * */
    searchReset() {
      this.query = {
        beginTime: dateFormat(new Date(), "yyyy-MM") + "-01 00:00:00",
        endTime: dateFormat(new Date(), "yyyy-MM-dd") + " 23:59:59"
      },
      this.search = {
        beginTime: dateFormat(new Date(), "yyyy-MM") + "-01 00:00:00",
        endTime: dateFormat(new Date(), "yyyy-MM-dd") + " 23:59:59"
      },
      Object.assign(this.query,this.searchParams)
      this.onLoad(this.page);
    },
    /**
     * @func 搜索
     * @desc 根据条件查询
     * @param {params} params --- 条件查询
     * */
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.refreshChange();
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.refreshChange();
    },

    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;
      let paramObj = {
        ...this.currentMer
      }
      
      getStoreList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query, paramObj)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * @func 导出
     * @desc 根据条件导出
     * */
    handleExport() {
      let exQuery = ``;
      // exQuery += `&industryCode=${this.search.industryCode}`;//客户经理
      exQuery += `&rptPayType=${this.search.rptPayType}`;
      // exQuery += `&rptPayModel=${this.search.rptPayModel}`;
      exQuery += `&rpiName=${this.search.rpiName}`;
      exQuery += `&rpiNo=${this.search.rpiNo}`;
      exQuery += `&rpsName=${this.search.rpsName}`;
      exQuery += `&rptOrderCode=${this.search.rptOrderCode}`;
      exQuery += `&rptOtherPayCode=${this.search.rptOtherPayCode}`;//官方订单号
      exQuery += `&rtNo=${this.search.rtNo}`;
      exQuery += `&rptRtNo=${this.search.rptRtNo}`;
      exQuery += `&rptAmount=${this.search.rptAmount}`;
      if (this.search.beginTime) {
        exQuery += `&beginTime=${this.search.beginTime}`;
      }
      if (this.search.endTime) {
        exQuery += `&endTime=${this.search.endTime}`;
      }

      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-core/core/platformProfit/platform_profit/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    /**
     * @func 排序
     * @desc 根据表格字段排序
     * */
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    }
  }
};
</script>

<style lang="scss" scoped>
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

.redFontBox {
  margin-right: 40px;
  .redFont {
    color: red;
  }
}
/deep/ .el-tag--dark.el-tag--success {
  border: none !important;
}

</style>